<script setup lang="ts">
import {ref, } from 'vue'
import type{FormInstance} from 'element-plus'
import {ElMessage as message} from 'element-plus'
import useRequestList from './requestList'
import mySelect from '@/components/Select/mySelect.vue'

const props = withDefaults(defineProps<{
	pageList?:{[key:string]:any}[]
}>(),{
  pageList:()=>([]),
})


const requestList=useRequestList()
const needAuthPage=ref(true)

const formLayout = {
	style: "margin: 0 10px",
  labelWidth: "auto",
  labelPosition: "left",
}


const rules = ref({
	requestName: [
		{ required: true, message: '请输入请求名！', trigger: 'change' },
		{ pattern: /^[a-zA-Z]+$/, message: '请求名只能包含英文！', trigger: 'change' },
	],
	requestPath: [{ required: true, message: '请输入请求路径！', trigger: 'change' }],
	needAuth: [{ required: true, message: '请选择是否需要授权访问！', trigger: 'change' }],
	description: [{ required: true, message: '请输入接口描述！', trigger: 'change' }],
	routeKeys: [{ required: true, message: '请输选择接口所在的页面！', trigger: 'change' }],
})

type dataType={
	requestName: string
	requestPath: string
	needAuth: 0|1
	description:string
	routeKeys:any[] 
	[key:string]:any
}

const initFormData: dataType = {
	requestName: '',
	requestPath: '',
	needAuth: 1,
	description: '',
	routeKeys:[],
}
const formData = ref<dataType>({ ...initFormData })

const formInstance = ref<FormInstance | null>(null)

function handleAuthChange(v:0|1){
	if(!v)  {
		rules.value.routeKeys[0].required=false
    needAuthPage.value=false
	 }else{
		rules.value.routeKeys[0].required=true
    needAuthPage.value=true
	 } 
}

function init() {
  formInstance.value?.resetFields();
  handleAuthChange(1)
}


async function formCommit() {
  try {
		await formInstance.value?.validate()
		let routeIds='',routeNames='',routeTitles=''
		if(formData.value.routeKeys.length)
		props.pageList.forEach(v=>{
			if(formData.value.routeKeys.includes(v.id)){
				  if(!routeIds) routeIds=v.id
          else routeIds+=","+v.id
				  if(!routeNames) routeNames=v.name
          else routeNames+=","+v.name
				  if(!routeTitles) routeTitles=v.title
          else routeTitles+=","+v.title
			}
    })
		let params:requestItem={...formData.value,routeIds,routeNames,routeTitles,id:`${Math.random()+Date.now()}_${formData.value.requestName}`}
		delete params.routeKeys
		const res=await requestList.addItem(params)
		if (res.code == 200) {
			return true
		}
		else if (res.code == 201)
			message.error('请求名已存在！')
		}catch(error){
        console.log(error)
		}
}

defineExpose({
  init,
  formCommit,
});
</script>

<template>
  <el-form
    :model="formData"
    :rules="rules"
    v-bind="formLayout"
    ref="formInstance"
  >
    <el-row :gutter="24">
      <el-col :span="12">
        <el-form-item prop="userName" label="请求名">
          <el-input
            v-model="formData.requestName"
            placeholder="请求名必须唯一，也用作请求的权限值。"
            clearable
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
					<el-form-item prop="needAuth" label="是否需要授权访问" >
						<mySelect v-model="formData.needAuth" placeholder="无需授权的话，则该接口任意角色可访问" clearable @change="handleAuthChange" :select-options="[
              {label:'是',value:1},
              {label:'否',value:0},
            ]"
            />
					</el-form-item>
				</el-col>
      <el-col :span="12">
        <el-form-item prop="requestPath" label="请求路径">
          <el-input
              v-model="formData.requestPath"
            placeholder="请输入接口的请求路径"
            clearable
          />
        </el-form-item>
      </el-col>

      <el-col :span="12">
        <el-form-item prop="description" label="接口描述">
          <el-input
            v-model="formData.description"
            placeholder="请输入接口描述"
            clearable
          />
        </el-form-item>
      </el-col>

      <el-col :span="24" v-show="needAuthPage">
        <el-form-item prop="routeKeys" label="所在的页面集合">
          <mySelect v-model="formData.routeKeys" placeholder="请选择该接口会出现在哪些页面"  style="width: 100%;" @change="handleAuthChange" :select-options="(pageList as any)"  multiple clearable 
          />
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
</template>
